package com.fengxu.gamescript.ui.main.mode.file

import android.animation.ValueAnimator
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.ImageButton
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.fengxu.gamescript.R
import com.fengxu.gamescript.data.GlobalData
import com.fengxu.gamescript.data.ScriptProp
import com.fengxu.gamescript.ui.main.MainActivity
import com.fengxu.gamescript.util.CommonUtils
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.xuexiang.xui.adapter.simple.XUISimpleAdapter
import com.xuexiang.xui.utils.DensityUtils
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText
import com.xuexiang.xui.widget.popupwindow.popup.XUIListPopup
import com.xuexiang.xui.widget.popupwindow.popup.XUIPopup
import com.xuexiang.xui.widget.toast.XToast
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.sdk27.coroutines.onEditorAction
import java.io.File

/**
 * 文件页
 */
class FileFragment : Fragment() {

    /**
     * 排序的imageBtn
     */
    private val orderImageBtn:ImageButton by lazy {
        requireActivity().findViewById(R.id.file_orderType)
    }

    /**
     * 排序规则的imageBtn
     */
    private val sortImageBtn:ImageButton by lazy {
        requireActivity().findViewById(R.id.file_sortType)
    }

    /**
     * 查看文件夹路径的imageBtn
     */
    private val folderImageBtn:ImageButton by lazy {
        requireActivity().findViewById(R.id.file_folderPath)
    }

    /**
     * 文件搜索框
     */
    private val searchTextView: MaterialEditText by lazy {
        requireActivity().findViewById(R.id.file_search)
    }

    /**
     * 刷新布局
     */
    private val refreshLayout:SmartRefreshLayout by lazy {
        requireActivity().findViewById(R.id.file_refreshLayout)
    }

    /**
     * 文件列表 list
     */
    private val fileListRecyclerView:RecyclerView by lazy {
        requireActivity().findViewById(R.id.file_list)
    }

    /**
     * 添加新文件按钮
     */
    private val newFileBtn: View by lazy {
        requireActivity().findViewById(R.id.file_addNewFile)
    }

    /**
     * 文件排序类型
     */
    enum class OrderType{
        Asc,    // 升序
        Desc    // 降序
    }

    /**
     * 文件排序规则
     */
    enum class SortRule{
        ByName,  // 通过名称
        ByTime,  // 通过最后修改时间
        BySize   // 通过文件大小
    }

    /**
     * 文件排序类型
     */
    var fileOrderType: OrderType = OrderType.Desc
        private set(value){
            field = value
            if(value == OrderType.Asc){
                orderImageBtn.setImageDrawable(resources.getDrawable(R.drawable.sort_up,null))
            }else{
                orderImageBtn.setImageDrawable(resources.getDrawable(R.drawable.sort_down,null))
            }
        }

    /**
     * 当前文件排序规则
     */
    var fileSortRole: SortRule = SortRule.ByName
        private set


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_file, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    /**
     * 初始化View
     */
    private fun initView() {
        // 设置扫描文件,并显示在RecyclerView中
        var linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        fileListRecyclerView.layoutManager = linearLayoutManager
        fileListRecyclerView.adapter = FileListAdapter(requireContext(),scanFile())
        // 添加排序类型btn的事件
        orderImageBtn.onClick {
            fileOrderType = if(fileOrderType == OrderType.Asc ){OrderType.Desc}else{OrderType.Asc}
            orderChanged()
        }
        // 添加排序规则事件
        val sortRoleList = listOf("名称","时间","大小")
        val roleAdapter = XUISimpleAdapter.create(context, sortRoleList)
        val xuiListPopup = XUIListPopup<Nothing>(context, roleAdapter)
        xuiListPopup.run {
            create(DensityUtils.dp2px(200F), DensityUtils.dp2px(150F)) {
                parent, view, position, id ->
                // 使用指定的排序规则排序脚本文件
                fileSortRole = SortRule.values()[position]
                var adapter = fileListRecyclerView.adapter as FileListAdapter
                adapter.scriptFileList = sortScriptFile(adapter.scriptFileList)
                fileListRecyclerView.adapter = adapter
                xuiListPopup.dismiss()
            }
            setHasDivider(true)
            setAnimStyle(XUIPopup.ANIM_GROW_FROM_CENTER);
            // 点击显示pop排序规则弹出项
            sortImageBtn.onClick {
                xuiListPopup.showDown(sortImageBtn)
            }
        }
        // 查看文件夹路径
        folderImageBtn.onClick {
            CommonUtils.toastDialog(requireContext(),content = "脚本文件夹路径为: ${GlobalData.MusicScriptFolderPath}")
        }
        // 搜索框搜索事件
        searchTextView.onEditorAction {
            v, actionId, event ->
            // 触发搜索
            if(actionId == EditorInfo.IME_ACTION_SEARCH){
                var adapter = fileListRecyclerView.adapter as FileListAdapter
                val searchRegex = searchTextView.editValue
                if(searchRegex.isEmpty()){
                    adapter.scriptFileList = scanFile()
                }else{
                    adapter.scriptFileList = adapter.scriptFileList.filter { scriptProp ->
                        Regex(searchRegex,RegexOption.DOT_MATCHES_ALL).containsMatchIn(scriptProp.name)
                    }.toMutableList()
                }
                fileListRecyclerView.adapter = adapter
            }
        }
        // 添加下拉刷新事件
        refreshLayout.setOnRefreshListener {
            refreshScriptList()
            it.finishRefresh()
        }
        // 添加新文件事件
        newFileBtn.onClick { createNewScript() }
        // 注册一个tab选项改变事件
        (requireActivity() as MainActivity).tabSelectChangeEvents.add(this::tabChanged)
    }

    // tab选项改变事件
    private fun tabChanged(index: Int){
        if(index == 0){
            // 执行进入动画
            fileFlowEnterAnim()
        }
    }

    /**
     * 刷新脚本列表
     */
    fun refreshScriptList(){
        var adapter = fileListRecyclerView.adapter as FileListAdapter
        adapter.scriptFileList = scanFile()
        fileListRecyclerView.adapter = adapter
    }

    /**
     * 创建新脚本
     */
    private fun createNewScript(){
        CommonUtils.inputDialog(requireContext(),"创建新脚本",hint = "文件名", content = "请输入新文件的名称",
            onPositive = {
                val file = File(GlobalData.MusicScriptFolderPath + "/${it}.js")
                if(file.exists()){
                    XToast.error(requireContext(),"已有相同名称的文件存在,文件创建失败!").show()
                }else{
                    file.createNewFile()
                    var adapter = fileListRecyclerView.adapter as FileListAdapter
                    adapter.scriptFileList.add(0, ScriptProp.getScriptByFile(file))
                    adapter.notifyItemInserted(0)
                    adapter.notifyDataSetChanged()
                }
            })
    }


    /**
     *  扫描文件获取脚本文件列表
     */
    private fun scanFile():MutableList<ScriptProp>{
        var list = mutableListOf<ScriptProp>()
        File(GlobalData.MusicScriptFolderPath).listFiles()
            .filter { it.name.toLowerCase().endsWith(".js") && it.isFile}
            .forEach { list.add(ScriptProp.getScriptByFile(it)) }
        return list
    }

    /**
     * 根据指定的排序规则排序脚本文件
     */
    private fun sortScriptFile(scriptList: MutableList<ScriptProp>):MutableList<ScriptProp>{
        return scriptList.sortedWith{
            s1,s2->
            when(fileSortRole){
                SortRule.ByName -> return@sortedWith s1.name.compareTo(s2.name)
                SortRule.BySize -> return@sortedWith (s2.size - s1.size).toInt()
                SortRule.ByTime -> return@sortedWith (s2.updateTime - s1.updateTime).toInt()
            }
        }.toMutableList()
    }

    /**
     * 排序规则发送改变(升序或者倒序)
     */
    private fun orderChanged(){
        var fileListAdapter = fileListRecyclerView.adapter as FileListAdapter
        fileListAdapter.scriptFileList = fileListAdapter.scriptFileList.reversed().toMutableList()
        fileListRecyclerView.adapter = fileListAdapter
    }

    /**
     * 设置添加新文件悬浮窗进入动画
     */
    private fun fileFlowEnterAnim(){
        val lp = newFileBtn.layoutParams
        var valueAnimator = ValueAnimator.ofInt(0, lp.height)
        valueAnimator.duration = 500
        valueAnimator.addUpdateListener {
            lp.width = it.animatedValue as Int
            lp.height = it.animatedValue as Int
            newFileBtn.layoutParams = lp
            newFileBtn.requestLayout()
        }
        valueAnimator.start()
    }


}